<template>
	<view class="zhanghao">
		<!-- 头像 -->
		<view class="userimg">
			<text class="userimgText">头像</text>
			<view class="img1">
				<button type="balanced" open-type="chooseAvatar" @chooseavatar="onChooseavatar">
					<image :src="userinfo.img"
						style="width: 120rpx; height: 120rpx;border-radius: 200rpx;overflow: hidden;"></image>
				</button>
			</view>
		</view>

		<!-- 名称 -->
		<view class="name">
			<text class="nameleft">昵称</text>
			<view class="nametext">
				<input type="nickname" :value="userinfo.name" @blur="bindblur" placeholder="请输入昵称" @input="bindinput"
					maxlength="6" />
			</view>
		</view>

		<!-- 性别 -->
		<view class="sex">
			<text class="sextext">性别</text>
			<view class="sexdx">
				<u-radio-group v-model="userinfo.sex" placement="row" @change="groupChange">
					<u-radio :customStyle="{marginBottom: '8px', marginLeft: '40rpx'}"
						v-for="(item, index) in radiolist1" :key="index" :label="item.name" :name="item.sexA">
					</u-radio>
				</u-radio-group>
			</view>
		</view>

		<view class="phone">
			<text class="phoneleft">手机号</text>
			<view class="phonetext">
				<!-- <u--input type="number" placeholder="请输入手机号" v-model="userinfo.phone" @change="phoneChange"></u--input> -->
				<!-- <input @input="phoneInput" :value="userinfo.phone" type="number" maxlength="11" /> -->
				<input class="uni-input" @input="phoneInput" v-model="userinfo.phone" type="number" maxlength="11" />
			</view>
		</view>

		<view class="button" @click="onSubmit">
			<text>修 改</text>
		</view>
	</view>
</template>

<script>
	// 从 vuex 中按需导入 mapState 辅助函数
	import {
		mapMutations,
		mapState
	} from 'vuex'

	export default {
		// 将 badgeMix 混入到当前的页面中进行使用
		computed: {
			...mapState('m_user', ['userinfo'])
		},
		data() {
			return {
				// 倒计时的秒数
				seconds: 3,
				// 定时器的 Id
				timer: null,
				
				radiolist1: [{
						sexA: 1,
						name: '男生',
						disabled: false
					},
					{
						sexA: 0,
						name: '女生',
						disabled: false
					},
				],
				img: '',
				avatarUrl: '',
				userSex: '',
				nickName: '',
				userPhone: '',
				my_policy: {},
				haveImg: false,

				newUserInfo: {
					id: '',
					wx_id: '',
					name: '',
					password: '',
					img: '',
					sex: '',
					phone: '',
					address: '',
					state: '',
					limitt: '',
					create_at: '',
					update_at: '',
					money: ''
				}
			};
		},
		onLoad(option) {
			this.getPoicy()
			
			this.img = this.userinfo.img
			this.userSex = this.userinfo.sex
			this.nickName = this.userinfo.name
			this.userPhone = this.userinfo.phone
			// console.log(this.nickName)
		},
		// watch: {
		// 	img: {
		// 		handler(newImg, oldImg) {
		// 			this.haveImg = true
		// 		},
		// 		immediate: true
		// 	}
		// },
		methods: {
			...mapMutations('m_user', ['updateUserInfo']),

			// 访问阿里云返回骑士杨账号
			async getPoicy() {
				const {
					data: res
				} = await uni.request({
					url: 'http://8.130.114.82:5555/bbm/goods/oss/policy',
					method: 'GET',
				})
				// console.log(res)
				this.my_policy = res.data 
				// console.log(this.my_policy)
			},

			// 上传至阿里云
			async upload() {
				// that指向this
				var that = this

				const host = this.my_policy.host;
				const signature = this.my_policy.signature;
				const ossAccessKeyId = 'LTAI5tCsKW7PKGs1hDXbMUzd'; 
				const policy = this.my_policy.policy;
				const key = this.my_policy.dir + this.userinfo.id +'.jpg';
				const filePath = this.avatarUrl; // 待上传文件的文件路径。

				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: host, // 开发者服务器的URL。
						filePath: filePath,
						name: 'file', // 必须填file。
						formData: {
							key,
							policy,
							OSSAccessKeyId: ossAccessKeyId,
							signature,
						},
						success: (res) => {
							if (res.statusCode === 204) {
								console.log('上传至阿里云成功 upload');
							}
							// console.log(res)
							// this.setData({
							// 	img: host + key
							// })
							that.img = host + "/" + key
							  
							console.log("更新后的头像地址："+this.img)

							resolve('suc'); // 千万别忘写！！！
							// console.log(that)
						},
						fail: err => {
							console.log(err); 
							console.log("上传头像失败 || 没修改头像");
							// reject('err')
						}
					})
				})
				// userSend && userSend(this.updateMyUserInfo)
			},
 
			// 修改至数据库
			async userSend() {  

				const {
					data: res
				} = await uni.request({
					url: 'http://8.130.114.82:5555/bbm/user/update',
					method: 'POST',
					data: {
						id: this.userinfo.id,
						img: this.img,
						name: this.nickName,
						sex: this.userSex,
						phone: this.userPhone
					}, 
					success: (res) => {
						// console.log(res)
						// console.log('上传成功');
						if (res.statusCode === 200) {
							console.log('上传至数据库成功 userSend');
						}
					},
					fail: err => {
						console.log(err);
						console.log("上传数据库失败");
					}
				})  
				// updateMyUserInfo && updateMyUserInfo(this.updateUserInfo)
			},

			// 头像 
			onChooseavatar(e) { 
				this.avatarUrl = e.detail.avatarUrl;
				// console.log("----"+this.avatarUrl) 
			},

			// 名字
			bindblur(e) {
				this.nickName = e.detail.value; // 获取微信昵称
				// console.log(this.nickName)
			},
			bindinput(e) {
				//这里要注意如果只用blur方法的话用户在输入玩昵称后直接点击保存按钮，会出现修改不成功的情况。
				this.nickName = e.detail.value;
			},

			// 性别
			groupChange(e) {
				// console.log(e) 
				this.userSex = e;
			},

			phoneInput(e) {
				// console.log(e)
				this.userPhone = e.detail.value
			},
		
			async updateMyUserInfo() {
				// 更新的信息
				this.newUserInfo.id = this.userinfo.id
				this.newUserInfo.name = this.nickName
				this.newUserInfo.img = this.img
				this.newUserInfo.sex = this.userSex
				this.newUserInfo.phone = this.userPhone 

				// 未改动的信息
				this.newUserInfo.wx_id = this.userinfo.wx_id
				this.newUserInfo.password = this.userinfo.password
				this.newUserInfo.address = this.userinfo.address
				this.newUserInfo.state = this.userinfo.state
				this.newUserInfo.limitt = this.userinfo.limit
				this.newUserInfo.create_at = this.userinfo.create_at
				this.newUserInfo.update_at = this.userinfo.update_at
				this.newUserInfo.money = this.userinfo.money

				console.log('更新updateMyUserInfo') 
				console.log(this.newUserInfo)
			},
			
			
			// 展示倒计时的提示消息
			async showTips(n) {
				// 调用 uni.showToast() 方法，展示提示消息
				uni.showToast({
					// 不展示任何图标
					icon: 'none',
					// 提示的消息
					title: '修改个人信息成功,' + n + ' 秒后自动跳转到主页',
					// 为页面添加透明遮罩，防止点击穿透
					mask: true,
					// 1.5 秒后自动消失
					duration: 1500
				})
			},
			
			// 延迟导航到 my 页面
			async delayNavigate() {
				// 把 data 中的秒数重置成 3 秒
				this.seconds = 3
			
				this.showTips(this.seconds)
				// 1. 将定时器的 Id 存储到 timer 中
				this.timer = setInterval(() => {
					this.seconds--
					// 2. 判断秒数是否 <= 0
					if (this.seconds <= 0) {
						// 2.1 清除定时器
						clearInterval(this.timer)
						// 2.2 跳转到 my 页面
						uni.switchTab({
							url: '/pages/my/my',
						})
			
						// 2.3 终止后续代码的运行（当秒数为 0 时，不再展示 toast 提示消息）
						return
					}
					this.showTips(this.seconds)
				}, 1000)
			},
			
			async onSubmit() {
				if (this.nickName === '') {
					uni.showToast({
						icon: 'none',
						title: '请输入昵称'
					})
					return false;
				}
				if (this.userPhone === '') {
					uni.showToast({
						icon: 'none',
						title: '手机号不可为空'
					})
					return false; 
				} else {
					var reg = /^1[3456789]\d{9}$/;
					console.log("电话号码："+this.userPhone)
					
					if (!reg.test(this.userPhone)) {
						uni.showToast({
							icon: 'none',
							title: '请输入有效的手机号码'
						})
						return false;
					}
				}

				if (this.avatarUrl !== "") {
					// 上传图片到阿里云
					// console.log(this.userinfo.img)
					// console.log("this") 
					
					await this.upload()
				}

				// 上传至数据库
				await this.userSend() 

				// 更新页面的 userinfo
				await this.updateMyUserInfo() 

				// 储存页面的 userinfo
				await this.updateUserInfo(this.newUserInfo)
				// console.log(this.newUserInfo.img) 
				
				console.log("修改信息成功!!!")
				
				// 跳转至主页
				await this.delayNavigate()

			}
		}
	};
</script>

<style lang="scss">
	.zhanghao {
		.userimg {
			margin-top: 20rpx;

			.userimgText {
				float: left;
				margin-top: 36rpx;
				margin-left: 16rpx;
			}

			.img1 {
				float: right;
				margin-right: 16rpx;

				button {
					background: none;
				}

				button::after {
					border: 0;
				}
			}
		}

		.name {
			clear: both;
			padding-top: 28rpx;

			.nameleft {
				margin-left: 16rpx;
			}

			.nametext {
				width: 170rpx;
				float: right;
			}
		}


		.sex {
			margin-top: 60rpx;
			margin-left: 16rpx;

			.sexdx {
				float: right;
				margin-right: 30rpx;
			}
		}


		.phone {
			margin-top: 60rpx;
			margin-left: 16rpx;
			clear: both;

			.phonetext {
				width: 234rpx;
				float: right;
				margin-right: 12rpx;
				color: #b0b2b4;
			}
		}


		.button {
			width: 720rpx;
			margin: 0 auto;
			margin-top: 100rpx;
			color: #fff;
			background-color: #3c9cff;
			border-color: #3c9cff;
			border-width: 1px;
			border-style: solid;
			border-bottom-left-radius: 8rpx;
			border-bottom-right-radius: 8rpx;
			border-top-left-radius: 8rpx;
			border-top-right-radius: 8rpx;
			height: 40px;
			position: relative;
			align-items: center;
			justify-content: center;
			display: flex;
			box-sizing: border-box;
			flex-direction: row;
		}

		/deep/.u-border {
			border: none;
		}

		/deep/.u-input--radius.data-v-4eec3aee,
		.u-input--square.data-v-4eec3aee {
			padding: 0 0;
		}

		/deep/ .u-input__content__field-wrapper__field.data-v-4eec3aee {
			color: #b0b2b4 !important;
		}
	}
</style>